<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Request;
use \app\index\model\Option;
use \app\index\model\User;
use \app\index\model\ShareBlackboardHandler;
use think\Session;

class BlackboardShare extends Controller{

    public function Create()
	{	
		$shareFiles = null;
		$originalFiles = null;
		$param = json_decode(file_get_contents("php://input"),true);
		if (array_key_exists("keys", $param)) {
			$shareFiles = $param['keys'];
		}
		if (array_key_exists("orinalNames", $param)) {
			$originalFiles = $param['orinalNames'];
		}
		if ($shareFiles == null) {
			echo "Bad request";
			exit();
		}
		$filesIds = [];
		foreach ($shareFiles as $fileKey) {
			$fileId = $this->getFileIdByFileKey($fileKey);
			if ($fileId != null && !in_array($fileId, $filesIds)) 
			{
				array_push($filesIds, $fileId);
			}
		}
		if ($originalFiles != null && count($originalFiles) > 0) {
			foreach ($originalFiles as $originalFile) {
				$fileId = $this->getFileIdByOriginalName($originalFile);
				if ($fileId != null && !in_array($fileId, $filesIds)) {
					array_push($filesIds, $fileId);
				}
			}
		}

		ShareBlackboardHandler::createBackbordShare($filesIds);

	}

	private function getFileIdByFileKey($preName)
	{
		$file = Db::name('files')
		->where('pre_name',$preName)
		->select();
		if (count($file) == 0 || count($file) > 1) {
			return null;
		}
		return $file[0]["id"];
	}

	private function getFileIdByOriginalName($originalName)
	{
		$file = Db::name('files')
		->where('orign_name',$originalName)
		->select();
		if (count($file) == 0 || count($file) > 1) {
			return null;
		}
		return $file[0]["id"];
	}

	public function Query()
	{
		$shareId = input('param.key');
		$shareBlackboard = Db::name('share_blackboard')
		->where('id',$shareId)
		->select();
		if (empty($shareBlackboard)) {
			echo "Bad request";
			exit();
		}
		$fileIdArray = explode(',', $shareBlackboard[0]['file_ids']);

		$policy = Db::name('policy')
		->where('id',2)
		->select();
		if (is_null($policy)) {
			echo "MetaData error, please set oss policy";
			exit();
		}
		$url = $policy[0]['url'];

		$imageUrls = [];
		foreach($fileIdArray as $fileId) {
			$file = Db::name('files')
			->where('id',$fileId)
			->select();
			array_push($imageUrls, $url.$file[0]['pre_name']);
		}

		return view('blackboard', [
			'imageUrls' => $imageUrls,
			'options'  => Option::getValues(['basic','share']),
		]);

	}


}
